#!/bin/bash

# AFR Website Build Script (Ubuntu/Linux)
echo -e "\033[32mStarting AFR Website Docker build...\033[0m"

# Set variables
IMAGE_NAME="afrwebsite"
TAG="latest"
OUTPUT_FILE="afrwebsite.tar"

# Check if Docker is running
echo -e "\033[33mChecking Docker status...\033[0m"
if ! docker version >/dev/null 2>&1; then
    echo -e "\033[31mDocker is not running or not installed, please start Docker\033[0m"
    exit 1
fi
echo -e "\033[32mDocker is running\033[0m"

# Stop and remove old container
echo -e "\033[33mCleaning up old containers...\033[0m"
docker stop afrwebsite-container >/dev/null 2>&1 || true
docker rm afrwebsite-container >/dev/null 2>&1 || true

# Remove old image
echo -e "\033[33mCleaning up old images...\033[0m"
docker rmi ${IMAGE_NAME}:${TAG} >/dev/null 2>&1 || true

# Build new image
echo -e "\033[33mBuilding Docker image...\033[0m"
if docker build -t ${IMAGE_NAME}:${TAG} .; then
    echo -e "\033[32mImage build successful!\033[0m"
else
    echo -e "\033[31mImage build failed!\033[0m"
    exit 1
fi

# Export image
echo -e "\033[33mExporting image file...\033[0m"
if docker save -o $OUTPUT_FILE ${IMAGE_NAME}:${TAG}; then
    echo -e "\033[32mImage export successful!\033[0m"
else
    echo -e "\033[31mImage export failed!\033[0m"
    exit 1
fi

# Show file information
echo -e "\033[36mFile information:\033[0m"
if [ -f "$OUTPUT_FILE" ]; then
    size=$(stat -f%z "$OUTPUT_FILE" 2>/dev/null || stat -c%s "$OUTPUT_FILE" 2>/dev/null)
    sizeMB=$(echo "scale=2; $size/1024/1024" | bc)
    echo -e "\033[36mImage file: $OUTPUT_FILE (${sizeMB} MB)\033[0m"
fi

# Show image information
echo -e "\033[36mImage information:\033[0m"
docker images | grep $IMAGE_NAME

echo -e "\033[32mBuild completed!\033[0m" 